package com.ahwei.web.filter;

import com.ahwei.pojo.Function;
import com.ahwei.pojo.User;
import com.ahwei.util.LogUtils;
import com.ahwei.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author：ahwei163@qq.com
 * @date: 202*-03-05 21:32:06
 * @description: 用户权限过滤器！
 */
@WebFilter(filterName = "PowerFilter", urlPatterns = "/*", initParams = {
        @WebInitParam(name = "whiteNameList",
                value = ".map;.js;.css;img/;upload/;.html;/showIndex;/userLogin;/checkCookie;/userRegister;"
                        + "/getVideoByTop;/getVideoList;/getVideoTypeList;/searchVideo;/registerCheck;html/test;"
                        + ".ico;/userExit;.woff;.ttf;css/;/showVideoDetail;")})
public class PowerFilter implements Filter {
    /*白名单列表*/
    private String[] whiteList;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //2.(*)获取虚拟目录：
        String contextPath = request.getContextPath();
        //3. 获取Servlet路径:/
        String servletPath = request.getServletPath();

        //检查请求是否在白名单中
        if (match(servletPath)) {
            //放行
            chain.doFilter(servletRequest, servletResponse);
        } else {
            //获取session中的用户
            User currentUser = (User) request.getSession().getAttribute("currentUser");
            LogUtils.info("currentUser = " + currentUser);
            //如果用户存在，表示已登录可以放行
            if (currentUser != null) {
                //获取用户功能列表（此功能列表在用户登录时创建）
                List<Function> funList = currentUser.getFunList();
                String str;
                //遍历用户功能列表
                for (Function fun : funList) {
                    //检查用户要访问的地址是否存在于列表中
                    if (fun.getFunUrl().contains(servletPath)) {
                        //存在则放行
                        chain.doFilter(servletRequest, servletResponse);
                        return;
                    }
                }
                str = "用户 [" + currentUser.getAccount() + "] 无此功能权限, 请联系管理员(权限编码: " + servletPath.substring(1) + ")";
                //servletRequest.getRequestDispatcher("showIndex").forward(servletRequest, servletResponse);
                LogUtils.error(str);
                response.setContentType("text/html;charset=utf-8");
                response.setStatus(403);
                response.getWriter().write(str);
                // response.sendRedirect("main.html?msg="+servletPath.substring(1));
            } else {
                //强制跳转回首页
                LogUtils.error("未登录!!!");
                response.setStatus(401);
                //response.sendRedirect("login.html");
                //servletRequest.getRequestDispatcher("login.html").forward(servletRequest, servletResponse);

                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("你好, 请登录!");
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        //获取web.xml的初始化参数
        String whiteNameList = config.getInitParameter("whiteNameList");
        whiteList = whiteNameList.split(";");
    }

    /**
     * 查询是否包含字符串
     *
     * @param str ·
     * @return ·
     */
    private boolean match(String str) {
        for (String s : whiteList) {
            if (str.contains(s)) {
                return true;
            }
        }
        return false;
    }

}
